import axios from 'axios'
import { Message } from 'element-ui'
import { getTimeToken } from '@/utils/auth'
import store from '@/store'
import router from '@/router'

const timeout = 1 * 3600 * 1000
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

// 请求拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    // 检查时间戳是否过期
    if (isCheckTimeOut()) {
      store.commit('user/logout')
      router.push('login')
      return Promise.reject(new Error('登录过期'))
    }
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(({ data }) => {
  const { data: res, message, success } = data
  if (success) return res
  Message.error(message)
  return Promise.reject(new Error(message))
}, error => {
  console.dir(error)
  if (error.response && error.response.status === 401) {
    store.commit('user/logout')
    router.push('login')
    Message.error('登录过期')
  } else {
    Message.error(error.message)
  }
  return Promise.reject(error)
})

// 判断token过期时间
function isCheckTimeOut() {
  const currentTime = Date.now()
  const tokenTime = getTimeToken()
  return (currentTime - tokenTime) >= timeout
}
export default service
